package com.ecoolex.hotel.saas.core.manager;

import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.CollectorUtil;
import com.ecoolex.hotel.saas.core.dao.PresaleCouponDistribtionDAO;
import com.ecoolex.hotel.saas.entity.Distribution;
import com.ecoolex.hotel.saas.entity.PresaleCouponDistribtion;
import com.ecoolex.hotel.saas.entity.PresaleCouponDistribtion.Column;
import com.ecoolex.hotel.saas.entity.PresaleCouponDistribtionExample;
import com.ecoolex.hotel.saas.entity.PresaleCouponDistribtionExample.Criteria;

import java.time.Instant;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PresaleCouponDistribtionManager {
	
    @Autowired
    private PresaleCouponDistribtionDAO dao;
    
    @Autowired
    private DistributionManager distributionManager;
    
    public void edit(Integer preCouponId, List<Integer> distributionIdList, String updateUser) {
    	List<PresaleCouponDistribtion> oldList = queryByPreCouponId(preCouponId);
    	if(Check.notNullOrEmpty(distributionIdList)) {
    		distributionIdList.forEach(d -> {
        		Distribution distribution = distributionManager.getDistribution(d);
        		BizAssert.isTrue(Check.notNull(distribution),ResultCode.BIZ.build(30), "分销配置不存在");
        		PresaleCouponDistribtion old = oldList.stream().collect(CollectorUtil.first(o -> o.getDistributionId().equals(d)));
        		if(Check.notNull(old)) {
        			oldList.remove(old);
        		}else {
        			PresaleCouponDistribtion record = new PresaleCouponDistribtion();
        			record.setPreCouponId(preCouponId);
        			record.setDistributionId(d);
        			record.setDeleted(PresaleCouponDistribtion.NOT_DELETED);
        			record.setCreateUser(updateUser);
        			record.setCreateTime(Date.from(Instant.now()));
        			record.setUpdateUser(updateUser);
        			record.setUpdateTime(Date.from(Instant.now()));
        			dao.insert(record);
        		}
        	});
    	}
    	oldList.forEach(o -> {
    		delete(o,updateUser);
    	});
    }
    
    public void delete(PresaleCouponDistribtion record, String updateUser) {
    	record.setDeleted(PresaleCouponDistribtion.IS_DELETED);
    	record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.deleted,Column.updateUser,Column.updateTime);
    }
    
    public List<PresaleCouponDistribtion> queryByPreCouponId(Integer preCouponId){
    	PresaleCouponDistribtionExample example = new PresaleCouponDistribtionExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andPreCouponIdEqualTo(preCouponId).andDeletedEqualTo(PresaleCouponDistribtion.NOT_DELETED);
    	return dao.selectByExample(example);
    }
}